package middleware

import (
	"bytes"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"io/ioutil"
	"libraryAutoGrab/db/mysql"
	"libraryAutoGrab/model/dto/input"
)

var dbClient = mysql.NewMysqlClient()

/**
 * @Description: 中间件，将请求信息写入mysql
 * @return gin.HandlerFunc
 */
func Log2Mysql() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		area := ctx.Query("area"); autoGrab := ctx.Query("autoGrab") == "true"
		body, _ := ioutil.ReadAll(ctx.Request.Body)
		ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
		var userinfo input.UserInfo
		json.Unmarshal(body, &userinfo)

		dbClient.Create(&mysql.Log{
			Model:    gorm.Model{},
			Userinfo: userinfo,
			Area:     area,
			AutoGrab: autoGrab,
		})
		ctx.Next()
	}
}
